import { ITouchEvent, View } from '@tarojs/components';
import classnames from 'classnames';
import { Children, Fragment, useMemo } from 'react';

import type { CSSProperties, FC, ReactNode } from 'react';

interface SpaceProps {
  className?: string;
  style?: CSSProperties;
  children?: ReactNode;
  direction?: 'horizontal' | 'vertical';
  justify?: 'flex-start' | 'flex-end' | 'center' | 'space-between';
  align?: 'flex-start' | 'flex-end' | 'center' | 'baseline';
  size?: CSSProperties['gap'];
  wrap?: boolean;
  block?: boolean;
  split?: boolean | ReactNode;
  onClick?: (e: ITouchEvent) => void;
}

import './index.scss';

const PREFIX_CLS = 'm-space';

// 检查React元素是否为空（null、undefined或只包含null的Fragment）
const isEmptyElement = (element: ReactNode): boolean => {
  if (element === null || element === undefined) {
    return true;
  }

  if (typeof element === 'string' || typeof element === 'number') {
    return false;
  }

  // 检查是否是Fragment且只包含null
  if (element && typeof element === 'object' && 'type' in element) {
    const reactElement = element as any;
    if (reactElement.type === Fragment) {
      const children = reactElement.props?.children;
      if (children === null || children === undefined) {
        return true;
      }
      // 如果是数组，检查是否所有元素都是null
      if (Array.isArray(children)) {
        return children.every((child) => isEmptyElement(child));
      }
      // 如果是单个元素，检查是否为null
      return isEmptyElement(children);
    }
  }

  return false;
};

const Space: FC<SpaceProps> = ({
  className,
  style,
  children,
  direction = 'horizontal',
  justify = 'flex-start',
  align = 'center',
  size = 8,
  wrap = true,
  block = false,
  split = false,
  onClick,
}) => {
  // 过滤出有效的子元素
  const validChildren = useMemo(() => {
    const valid: ReactNode[] = [];
    Children.forEach(children, (child) => {
      if (!isEmptyElement(child)) {
        valid.push(child);
      }
    });
    return valid;
  }, [children]);

  return (
    <View
      className={classnames(PREFIX_CLS, className)}
      style={{
        ...style,
        display: block ? 'flex' : 'inline-flex',
        flexDirection: direction === 'horizontal' ? 'row' : 'column',
        justifyContent: justify,
        alignItems: align,
        gap: size,
        flexWrap: wrap ? 'wrap' : 'nowrap',
      }}
      onClick={onClick}
    >
      {validChildren.map((child, index) => {
        return (
          <Fragment key={index}>
            <View
              className={classnames(`${PREFIX_CLS}-item`, {
                [`${PREFIX_CLS}-item-single`]: validChildren.length === 1,
              })}
            >
              {child}
            </View>
            {split && index !== validChildren.length - 1 ? (
              <View className={`${PREFIX_CLS}-split`}>
                {split && split !== true ? (
                  split
                ) : (
                  <View className={`${PREFIX_CLS}-split-divider`} />
                )}
              </View>
            ) : null}
          </Fragment>
        );
      })}
    </View>
  );
};

export default Space;
